package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> add(@RequestBody DishDto dishDto) {
        log.info("dish:{}", dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功!");
    }


    @GetMapping("/page")
    public R<Page> save(int page, int pageSize, String name) {
        Page<Dish> pageDish = new Page<>(page, pageSize);
        Page<DishDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageDish, lambdaQueryWrapper);


        //对象拷贝,并且不拷贝record这个属性
        BeanUtils.copyProperties(pageDish, dtoPage, "records");
        List<Dish> records = pageDish.getRecords();
        List<DishDto> list = records.stream().map((items) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(items, dishDto);
            Long categoryId = items.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    //    @GetMapping("/list")
//    public R<List<Dish>> list(Long categoryId, String name) {
//        if (name == null) {
//            log.info("要查询的id{}", categoryId);
//            //根据categoryId查数据
//            LambdaQueryWrapper<Dish> lwq = new LambdaQueryWrapper<>();
//            lwq.eq(Dish::getCategoryId, categoryId);
//            lwq.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//            List<Dish> list = dishService.list(lwq);
//            return R.success(list);
//        } else {
//            log.info("要查询的name{}", name);
//            //根据name相似查询
//            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//            lqw.like(Dish::getName, name);
//            lqw.orderByDesc(Dish::getUpdateTime);
//            List<Dish> list = dishService.list(lqw);
//            return R.success(list);
//        }
//    }
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //构造查询条件
        LambdaQueryWrapper<Dish> lqw =new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        lqw.eq(dish.getName()!=null,Dish::getName,dish.getName());
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);
        List<DishDto> dtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dtoList);
    }

    /**
     * 根据id查询菜品信息和口味
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        log.info("要回显的数据id{}", id);
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateDishWithFlavor(dishDto);
        return R.success("菜品数据更新成功!");
    }


    /**
     * 删除商品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long[] ids) {
        log.info("要删除的菜品:{}", Arrays.toString(ids));
        dishService.deleteDishWithFlavor(ids);
        return R.success("删除成功!");
    }


    /**
     * 更新商品状态
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(
            @PathVariable("status") int status,
            @RequestParam("ids") Long[] ids
    ) {
        log.info("请求的id{},要改成的状态{}", Arrays.toString(ids), status);
        for (Long id : ids) {
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Dish::getId, id);
            Dish dish = dishService.getOne(lqw);
            //设置状态后更新
            dish.setStatus(status);
            //根据id更新操作
            dishService.updateById(dish);
        }
        return R.success("更新状态成功!");
    }
}
